package com.ljkj.cordial.chat.adapter;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.lanjiu.lib.imclient.user.UserPreferences;
import com.lanjiu.lib.utils.sp.SPKeys;
import com.lanjiu.lib.utils.sp.SharedPreferenceHelper;
import com.ljkj.cordial.chat.R;
import com.ljkj.cordial.chat.activity.VideoPlayActivity;
import com.ljkj.cordial.chat.bean.Canstants;
import com.ljkj.cordial.chat.bean.PayLoad;
import com.ljkj.cordial.chat.dao.AlbumTableBean;
import com.ljkj.cordial.chat.util.AlbumManageUtil;
import com.ljkj.cordial.chat.util.ObserverThread;
import com.ljkj.cordial.chat.util.SpeechVoiceUtil;
import com.ljkj.cordial.chat.widget.CommonHintDialog;
import com.nic.view.ViewConfig;
import com.nic.view.util.AndroidFileUtil;
import com.nic.view.util.glide.GlideUtil;
import com.yanzhenjie.album.AlbumFile;
import com.yanzhenjie.album.util.AlbumUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class FileMAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    private List<AlbumFile> list;
    private SparseArray<Boolean> booleanSparseArray = new SparseArray<>();
    private AudioManager am;

    public void setList(List<AlbumFile> list) {
        if (list == null || list.isEmpty()) {
            return;
        }
        this.list = list;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_file_manage, null,false);
        return new MViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int i) {
        AlbumFile item = list.get(i);
        MViewHolder mViewHolder = (MViewHolder) holder;
        Context context = mViewHolder.itemView.getContext();
        if (am == null && context != null)
            am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        mViewHolder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                booleanSparseArray.put(i, isChecked);
                if (onItemClickListener != null) {
                    onItemClickListener.onItem(FileMAdapter.this, buttonView, item, i, isChecked);
                }
            }
        });
        boolean b = booleanSparseArray.get(i, false);
        if (b) {
            mViewHolder.checkBox.setChecked(true);
        } else {
            mViewHolder.checkBox.setChecked(false);
        }
        if (!TextUtils.isEmpty(item.getPath())) {
            int mineType = AlbumTableBean.getFileType(item.getPath());
            int drawId = AlbumTableBean.getMineType(true, item.getPath());
            if (AlbumTableBean.TYPE_VIDEO == mineType) {
                String tag = (String) mViewHolder.ivFileType.getTag(com.nic.view.R.id.glide_image_id);
                if (TextUtils.isEmpty(tag) || tag.equals(item.getPath())) {
                    mViewHolder.ivFileType.setTag(com.nic.view.R.id.glide_image_id, item.getPath());
                }
                GlideUtil.getInstance().load(item.getPath(), mViewHolder.ivFileType);
//                ObserverThread.create().onNextThread0(new ObserverThread.OnActionListener<Bitmap>() {
//                    @Override
//                    public void onAction(Bitmap bmp) {
//                        if (bmp != null) {
//                            GlideUtil.getInstance().loadSmall(bmp, mViewHolder.ivFileType);
//                        }
//                    }
//
//                    @Override
//                    public Bitmap onThreadAction() {
//                        return AlbumUtils.takePicture(item.getPath());
//                    }
//                });
                GlideUtil.getInstance().loadSmall(item.getPath(), mViewHolder.ivFileType);
                mViewHolder.ivIsVideo.setVisibility(View.VISIBLE);
                mViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
//                        VideoPlayActivity.jumpTo(context, item.getPath(), null);
                        Intent intent = AndroidFileUtil.openFile(item.getPath());
                        if (intent != null) {
                            v.getContext().startActivity(intent);
                            SpeechVoiceUtil.setAudioMute(v.getContext(), false);
                        }
                    }
                });
            } else if (AlbumTableBean.TYPE_IMAGE == mineType) {
                String tag = (String) mViewHolder.ivFileType.getTag(com.nic.view.R.id.glide_image_id);
                if (TextUtils.isEmpty(tag) || tag.equals(item.getPath())) {
                    mViewHolder.ivFileType.setTag(com.nic.view.R.id.glide_image_id, item.getPath());
                }
                GlideUtil.getInstance().load(item.getPath(), mViewHolder.ivFileType);
                mViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        AlbumManageUtil
                                .getInstance().lookLargePhoto(v.getContext(), item.getPath());
                    }
                });
            } else {
                mViewHolder.ivFileType.setImageResource(drawId);
                mViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (AlbumTableBean.isRecordFile(item.getPath())) {
                            String key = SPKeys.Key.CONFIG_VOICE_PLAY_BY_MAC + UserPreferences.getUserId();
                            boolean isMac = SharedPreferenceHelper.create(SPKeys.Name.CONFIG).getBoolean(key, Canstants.DEFAULT_MAC);
                            if (am != null) {
                                am.setSpeakerphoneOn(!isMac);
                                am.setMode(isMac ? AudioManager.MODE_IN_CALL : AudioManager.MODE_NORMAL);
                            }
                            AlbumManageUtil.getInstance().playVoice(item.getPath(), isMac, new AlbumManageUtil.OnPlayAnimListener() {
                                @Override
                                public void onStartAnim() {
                                }

                                @Override
                                public void onStopAnim() {
                                }
                            });
                            new CommonHintDialog(v.getContext()).setContent(item.getPath()).setSingleSubmitGray("取消", new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    AlbumManageUtil.getInstance().stopVoice();
                                }
                            }).show();
                        } else {
                            Intent intent = AndroidFileUtil.openFile(item.getPath());
                            if (intent != null) {
                                context.startActivity(intent);
                            }
                        }
                    }
                });
            }
            if (!TextUtils.isEmpty(item.getPath())) {
                try {
                    mViewHolder.tvTitle.setText(getFileName(item.getPath()));
                    Date date = new Date();
                    date.setTime(item.getAddDate());
                    mViewHolder.tvContent.setText(format.format(date));
                    mViewHolder.tvContent2.setText(getFileSize(item.getSize()));
                } catch (Exception e) {
                }
            }
        }
        mViewHolder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                new CommonHintDialog(v.getContext()).setTitle("是否删除当前文件").setContent(item.getPath()).setLeftSubmit("取消", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                }).setRightSubmit("删除", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        list.remove(i);
                        File file = new File(item.getPath());
                        if (file.exists()) {
                            file.delete();
                        }
                        notifyItemRemoved(i);
                        notifyItemRangeChanged(i, getItemCount());
//                        notifyItemRangeRemoved(i, getItemCount());
                    }
                }).show();
                return true;
            }
        });
    }

    //读取指定目录下的所有TXT文件的文件内容
    private String getFileContent(String path) {
        if (TextUtils.isEmpty(path)) {
            return "";
        }
        File file = new File(path);
        if (!file.exists()) {
            return "";
        }
        String content = "";
        if (!file.isDirectory()) {  //检查此路径名的文件是否是一个目录(文件夹)
            if (file.getName().endsWith("txt")) {//文件格式为""文件
                try {
                    InputStream instream = new FileInputStream(file);
                    if (instream != null) {
                        InputStreamReader inputreader
                                = new InputStreamReader(instream, "UTF-8");
                        BufferedReader buffreader = new BufferedReader(inputreader);
                        String line = "";
                        //分行读取
                        while ((line = buffreader.readLine()) != null) {
                            content += line + "\n";
                        }
                        instream.close();//关闭输入流
                    }
                } catch (java.io.FileNotFoundException e) {
//                    Log.d("TestFile", "The File doesn't not exist.");
                } catch (IOException e) {
//                    Log.d("TestFile", e.getMessage());
                }
            }
        }
        return content;
    }

    public void selectedAll() {
        if (list != null && !list.isEmpty()) {
            return;
        }
        notifyItemRangeChanged(0, list.size(), PayLoad.create(PayLoad.SELECTED));
    }

    public void unselectAll() {
        if (list != null && !list.isEmpty()) {
            return;
        }
        notifyItemRangeChanged(0, list.size(), PayLoad.create(PayLoad.UNSELECT));
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position, @NonNull List<Object> payloads) {
        super.onBindViewHolder(holder, position, payloads);
        if (payloads == null || payloads.isEmpty()) {
            onBindViewHolder(holder, position);
        } else {
            PayLoad payLoad = (PayLoad) payloads.get(0);
            MViewHolder mViewHolder = (MViewHolder) holder;
            for (int type : payLoad.getType()) {
                if (PayLoad.SELECTED == type) {
                    mViewHolder.checkBox.setChecked(true);
                    booleanSparseArray.put(position, true);
                }
                if (PayLoad.UNSELECT == type) {
                    mViewHolder.checkBox.setChecked(false);
                    booleanSparseArray.put(position, false);
                }
            }
        }
    }

    private void longClickRemove() {
        //        mViewHolder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
//            @Override
//            public boolean onLongClick(View v) {
//                new CommonHintDialog(context)
//                        .setTitle("删除条目")
//                        .setLeftSubmit("取消", new View.OnClickListener() {
//                            @Override
//                            public void onClick(View v) {
//
//                            }
//                        })
//                        .setRightSubmitGray("确认", new View.OnClickListener() {
//                            @Override
//                            public void onClick(View v) {
//                                remove(i);
//                            }
//                        }).show();
//                return true;
//            }
//        });
    }

//    public void remove(int position) {
//        AlbumTableBean item = list.get(position);
//        DbController.getInstance().getWrite().delete(item);
//        list.remove(position);
//        notifyItemRemoved(position);
//        notifyItemRangeChanged(position, list.size());
//    }


    private String getFileName(String path) {
        if (TextUtils.isEmpty(path)) {
            return null;
        }
        if (path.contains("/")) {
            String name = path.substring(path.lastIndexOf("/") + 1, path.length());
            if (name.contains(".")) {
                String endxx = name.substring(name.lastIndexOf("."), name.length());
                String stxx = name.substring(0, name.lastIndexOf("."));
                if (stxx.length() > 15) {
                    stxx = stxx.substring(0, 15) + "...";
                }
                return stxx + endxx;
            }
            return path.substring(path.lastIndexOf("/") + 1, path.length());
        }
        return path;
    }

    //    private String getFileSize(String path) {
//        if (TextUtils.isEmpty(path)) {
//            return 0 + "B";
//        }
//        if (0.0f != FileSizeUtil.getFileOrFilesSize(path, FileSizeUtil.SIZETYPE_MB)) {
//            return FileSizeUtil.getFileOrFilesSize(path, FileSizeUtil.SIZETYPE_MB) + "M";
//        } else if (0.0f != FileSizeUtil.getFileOrFilesSize(path, FileSizeUtil.SIZETYPE_KB)) {
//            return FileSizeUtil.getFileOrFilesSize(path, FileSizeUtil.SIZETYPE_KB) + "KB";
//        } else if (0.0f != FileSizeUtil.getFileOrFilesSize(path, FileSizeUtil.SIZETYPE_B)) {
//            return FileSizeUtil.getFileOrFilesSize(path, FileSizeUtil.SIZETYPE_B) + "B";
//        }
//        return 0 + "B";
//    }
    public String getFileSize(Long length) {
        DecimalFormat df = new DecimalFormat("0.00");//设置保留位数
        if (length >= 1048576) {
            return df.format((double) length / 1048576) + "MB";
        } else if (length >= 1024) {
            return df.format((double) length / 1024) + "KB";
        } else if (length < 1024) {
            return df.format((double) length) + "B";
        } else {
            return "0B";
        }
    }

    @Override
    public int getItemCount() {
        return list == null ? 0 : list.size();
    }

    static class MViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.iv_file_type)
        ImageView ivFileType;
        @BindView(R.id.iv_is_video)
        ImageView ivIsVideo;
        @BindView(R.id.tv_title)
        TextView tvTitle;
        @BindView(R.id.tv_content)
        TextView tvContent;
        @BindView(R.id.tv_content2)
        TextView tvContent2;
        @BindView(R.id.check_box)
        CheckBox checkBox;

        MViewHolder(View view) {
            super(view);
            ButterKnife.bind(this, view);
        }
    }

    private OnFileItemClickListener onItemClickListener;

    public void setOnItemClickListener(OnFileItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    public interface OnFileItemClickListener {
        void onItem(FileMAdapter adapter, View v, AlbumFile item, int position, boolean isChecked);
    }
}
